package com.example.wavcat

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.net.toFile
import com.example.wavcat.WavMergeUtil.mergeWav
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File


class MainActivity : AppCompatActivity() , OnRequestPermissionsResultCallback{
//    var wav1Path = "MIUI/sound_recorder/1.wav"
//    var wav2Path = "MIUI/sound_recorder/2.wav"
    var wav1Uri:File ?= null
    var wav2Uri:File ?= null
    val STORAGE_REQ_CODE = 1234

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (PermissionUtils.isGrantExternalRW(this, 1)) {
            btn_wav1.setOnClickListener{
                fileIndex = 1;
                selectFile()
            }
            btn_wav2.setOnClickListener{
                fileIndex = 2;
                selectFile()
            }
            btn_cat.setOnClickListener {
                val sdcard = Environment.getExternalStorageDirectory().path
                Log.d("wxx", "点击拼接按钮，sdcard：" + sdcard)

                if (wav1Uri==null || wav2Uri==null){
                    Toast.makeText(this, "请先选择待拼接的wav文件", Toast.LENGTH_SHORT).show()
                } else {

                    val file1 = wav1Uri!!
                    val file2 = wav2Uri!!
                    val outfile = File(sdcard + File.separator + "one.wav")
                    mergeWavFiles(file1, file2, outfile)
                }
//                val file1 = File(sdcard + File.separator + wav1Path)
//                val file2 = File(sdcard + File.separator + wav2Path)
//
//                mergeWavFiles(file1, file2, outfile)
            }
        }
    }

    val REQUEST_CHOOSEFILE = 2000
    var fileIndex = 1;
    fun selectFile(){
        val intent = Intent(Intent.ACTION_GET_CONTENT);
        //val intent = Intent(Intent.ACTION_PICK);

        intent.setType("audio/wav"); //选择音频
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        startActivityForResult(intent, REQUEST_CHOOSEFILE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("wxx", "onActivityResult requestCode:" + requestCode + " resultCode:" + resultCode)
        if (requestCode == REQUEST_CHOOSEFILE) {
            if (resultCode == Activity.RESULT_OK) {
                Log.d("wxx", "onActivityResult Intent：" + data.toString())
                val filepath = data?.getExtras()?.getString("file", "")
                Log.d("wxx", "filepath：" + filepath)


                var filePathFromActivity = data?.getExtras()?.get(Intent.EXTRA_STREAM)
                Log.d("wxx", "filePathFromActivity：" + filePathFromActivity)




                data?.data?.let {
                    //val filename = it.getLastPathSegment()!!
                    Log.d("wxx", "selected file  path:" + it.path)

                    val file = File(getFileAbsolutePathFromContentUri(it))
                    if (fileIndex == 1) {
                        wav1Uri = file
                        tv1.text = it.path
                    }else{
                        wav2Uri = file
                        tv2.text = it.path
                    }
                }
            }
        }
    }

    fun getFileAbsolutePathFromContentUri(contentUri:Uri) : String{
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        val cursor: Cursor = this.managedQuery(contentUri, proj, null, null, null)
        val column_index: Int = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor.moveToFirst()

        return cursor.getString(column_index);
    }

    fun mergeWavFiles(wavFile1: File, wavFile2: File, outFile: File){
        Log.d("wxx", "<--  mergeWavFiles")
        val startMs = System.currentTimeMillis()
        tv_result.text = "拼接开始 》"
        var inputLists:ArrayList<File> = ArrayList(2)
        inputLists.add(wavFile1)
        inputLists.add(wavFile2)
        mergeWav(inputLists, outFile)
        val endMs = System.currentTimeMillis()
        val usedMs = endMs - startMs
        tv_result.text = "拼接完成！文件路径：${outFile.absoluteFile}, 耗时${usedMs} ms"
        Toast.makeText(this, "拼接完成！", Toast.LENGTH_SHORT).show()
        Log.d("wxx", ">--  mergeWavFiles")

    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String?>,
        grantResults: IntArray
    ){
        when (requestCode) {
            STORAGE_REQ_CODE -> {
                var ret = true
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        ret = false
                        //检验是否获取权限，如果获取权限，外部存储会处于开放状态，会弹出一个toast提示获得授权
//                        val sdCard: String = Environment.getExternalStorageState()
//                        if (sdCard == Environment.MEDIA_MOUNTED) {
//                            Toast.makeText(this, "获得授权", Toast.LENGTH_LONG).show()
//                        }
                    }
                }
                if (!ret) {
                    runOnUiThread {
                        Toast.makeText(this@MainActivity, "权限不足", Toast.LENGTH_SHORT).show()
                    }
                } else {
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }
}